package org.novelhibernate.core.connection;

import java.sql.DriverManager;
import java.sql.SQLException;


import org.novelhibernate.core.transaction.Transaction;
import org.novelhibernate.core.transaction.TransactionImpl;


/**
 * 
 * This is the DriverManager-driven connection factory, which acquire connection
 * from DriverManager
 * 
 * 
 * @author Tao Chen
 *
 */
public class DriverManagerTransactionFactory implements ConnectionFactory {

	
	private static DriverManagerTransactionFactory factory;
	
	private String url;
	private String username;
	private String password;
	


	
	private DriverManagerTransactionFactory() {
	
	}

	
	public static DriverManagerTransactionFactory getInstance(){
		
		if(null == factory)
			factory = new DriverManagerTransactionFactory();
		
		return factory;
	}
	
	
	
	/**
	 * Configure the factory by given username, password and driver class path
	 * @param username
	 * @param password
	 * @param url
	 * @param driverPath
	 * @throws ClassNotFoundException 
	 */
	public void config(String username, String password, 
			 String url, String driverPath) throws ClassNotFoundException {
	
		this.username = username;
		this.password = password;
		this.url = url;
		Class.forName(driverPath);
	}
	
	@Override
	public Transaction createTransaction(boolean autoCommit,
			int transactionIsolation, boolean isRecordResult) throws SQLException {

		return new TransactionImpl((username == null) ? DriverManager.getConnection(url) : DriverManager.getConnection(url,
				                     username, password), autoCommit, transactionIsolation, isRecordResult);

	}

}
